package com.zhihaoliang.coroutine.buss.flow.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/25 16:16
 * @des Composing multiple flows : zip vs Combine
 */
object FlowCompose {

    fun onCompose(mainScope: CoroutineScope) = mainScope.launch {
        val num = (1..3).asFlow() // numbers 1..3
        val str = flowOf("one", "two", "three","four") // strings
        num.zip(str) { a, b -> "$a -> $b" } // compose a single string
            .collect { log("zip : $it") } // collect and print

        val num1 = (1..3).asFlow().onEach { delay(300) } // numbers 1..3 every 300 ms
        val str1 = flowOf("one", "two", "three","four").onEach { delay(400) } // strings every 400 ms
        val startTime = System.currentTimeMillis() // remember the start time
        num1.zip(str1) { a, b -> "$a -> $b" } // compose a single string with "zip"
            .collect { value -> // collect and print
                log("zip delay : $value at ${System.currentTimeMillis() - startTime} ms from start")
            }

        num1.combine(str1) { a, b -> "$a -> $b" } // compose a single string with "combine"
            .collect { value -> // collect and print
                log("combine delay : $value at ${System.currentTimeMillis() - startTime} ms from start")
            }
    }
}